import $ from 'jquery';

let config = {
  event: {}
};
export function hint(msg){
  window.console && console.error && console.error('Layui hint: ' + msg);
};

export function device(key) {
  var agent = navigator.userAgent.toLowerCase()

    //获取版本号
    , getVersion = function (label) {
      var exp = new RegExp(label + '/([^\\s\\_\\-]+)');
      label = (agent.match(exp) || [])[1];
      return label || false;
    }

    //返回结果集
    , result = {
      os: function () { //底层操作系统
        if (/windows/.test(agent)) {
          return 'windows';
        } else if (/linux/.test(agent)) {
          return 'linux';
        } else if (/iphone|ipod|ipad|ios/.test(agent)) {
          return 'ios';
        } else if (/mac/.test(agent)) {
          return 'mac';
        }
      }()
      , ie: function () { //ie版本
        return (!!win.ActiveXObject || "ActiveXObject" in win) ? (
          (agent.match(/msie\s(\d+)/) || [])[1] || '11' //由于ie11并没有msie的标识
        ) : false;
      }()
      , weixin: getVersion('micromessenger')  //是否微信
    };

  //任意的key
  if (key && !result[key]) {
    result[key] = getVersion(key);
  }
  //移动设备
  result.android = /android/.test(agent);
  result.ios = result.os === 'ios';
  return result;
};
export function onevent(modName, events, callback) {
  if (typeof modName !== 'string'
    || typeof callback !== 'function') return this;
  config.event[modName + '.' + events] = [callback];
  return this;
}
export function event(modName, events, params) {
  var that = this
    , result = null
    , filter = events.match(/\(.*\)$/) || [] //提取事件过滤器
    , set = (events = modName + '.' + events).replace(filter, '') //获取事件本体名
    , callback = function (_, item) {
      var res = item && item.call(that, params);
      res === false && result === null && (result = false);
    };
  each(config.event[set], callback);
  filter[0] && each(config.event[events], callback); //执行过滤器中的事件
  return result;
}
export function each(obj, fn) {
  let key;
  const that = this;
  if (typeof fn !== 'function') return that;
  obj = obj || [];
  if (obj.constructor === Object) {
    for (key in obj) {
      if (fn.call(obj[key], key, obj[key])) break;
    }
  } else {
    for (key = 0; key < obj.length; key++) {
      if (fn.call(obj[key], key, obj[key])) break;
    }
  }
  return that;
}